package com.blog.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.blog.entity.User;
import com.blog.service.UserService;
import com.blog.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
public class UploadController {

    @Value("${file.upload.path}")
    private String uploadPath;

    @Value("${file.access.path}")
    private String accessPath;
    
    @Autowired
    private UserService userService;

    @PostMapping("/image")
    public ResponseEntity<Map<String, String>> uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body(null);
        }

        try {
            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            // 获取文件后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 生成新的文件名
            String fileName = UUID.randomUUID().toString() + suffix;
            
            // 保存文件
            String filePath = FileUtils.saveFile(file, uploadPath, fileName);
            
            // 返回访问URL
            String url = accessPath + "/" + fileName;
            
            Map<String, String> result = new HashMap<>();
            result.put("url", url);
            result.put("name", fileName);
            
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().body(null);
        }
    }
    
    @PostMapping("/avatar")
    public ResponseEntity<Map<String, String>> uploadAvatar(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body(null);
        }
        
        // 检查用户是否已登录
        if (!StpUtil.isLogin()) {
            return ResponseEntity.status(401).body(null);
        }
        
        Long userId = StpUtil.getLoginIdAsLong();

        try {
            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            // 获取文件后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 生成新的文件名
            String fileName = "avatar_" + userId + "_" + UUID.randomUUID().toString() + suffix;
            
            // 保存文件
            String filePath = FileUtils.saveFile(file, uploadPath + "/avatars", fileName);
            
            // 返回访问URL
            String url = accessPath + "/avatars/" + fileName;
            
            // 更新用户头像
            User user = userService.getById(userId);
            if (user != null) {
                user.setAvatar(url);
                userService.updateById(user);
            }
            
            Map<String, String> result = new HashMap<>();
            result.put("url", url);
            result.put("name", fileName);
            
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().body(null);
        }
    }
} 